<template>
  <div class="category">
    <goback :getName='goName' :getURL ="goType" :getBtn='goBtn'></goback>
    <!-- 搜索 -->
    <section class="seach">
      <input type="text" placeholder="请输入商品名称" v-model="seachCnt">
      <section @click="seach">
        <img src="../../assets/other/seach.png" alt="" >
      </section>
    </section>
    <!-- 商品区 -->
    <section class="goods">
      <!-- 左边菜单 -->
      <section class="goods_category" ref="goods_category">
        <section v-for="(categoryList,index) in categoryList" :key="index" @click="showTwoLevel(categoryList.id);Initialize(index)">
          <!-- <router-link :to="'/category/'+categoryList.id+'/'+index" replace> -->
            <a>{{categoryList.classifyName}}</a>
          <!-- </router-link> -->
          <section class="redBox">
          </section>
        </section>
      </section>
      <!-- 商品详情 -->
      <section class="goodsList" ref="goodsList">
          <!-- 排序 -->
          <div class="twoLevelMenu" v-if="ifShowTwo">
            <div class="classfify">
              <div class="twoLevelClass" v-for="(e,index) of twoLevelMenu" @click="turnTwoLevel(e.id)">{{e.classifyName}}</div>
            </div>
          </div>
          <section class="seachTit">
            <section @click="sortFnc('sell')">
              <span>销量</span>
              <img src="../../assets/other/ASC.png" alt="" v-if="saleSort == 'ASC'">  
              <img src="../../assets/other/DESC.png" alt=""  v-if="saleSort == 'DESC'">  
            </section>
            <section  @click="sortFnc('defaultPrice')">
              <span>价格</span>
              <img src="../../assets/other/ASC.png" alt=""  v-if="priceSort == 'ASC'">  
              <img src="../../assets/other/DESC.png" alt=""  v-if="priceSort == 'DESC'">  
            </section>
          </section>
        <section class="goodsList_s" ref="goodsList_s" v-infinite-scroll="loadMore" infinite-scroll-disabled="loading" infinite-scroll-distance="10" infinite-scroll-immediate-check="loading">
            <a v-for="(goodsList,index) in goodsList" :key="index" @click="seeSec(goodsList.id)">
              <section class="goodsList_sec">
                <section class="_img">
                  <img v-bind:src="goodsList.thumbnail" alt="">
                </section>
                <section class="_sec">
                  <p class="_sec_tit">
                    {{goodsList.name}}
                  </p>
                  <p class="_sec_price">
                    {{goodsList.defaultPrice/100 | currency}}
                  </p>
                  <section class="_sec_btn"> 
                    <section v-if="userInfo.channelLv!=-1" class="cateSec" @click="lookEarnings(goodsList.clearPrice, goodsList.defaultPrice)" @click.stop>
                      收益
                    </section>
                    <section v-if="userInfo.channelLv ==-1">
                    </section>
                    <section class="cateImg">
                      <img src="../../assets/mall/mallCart.png" alt="">
                    </section>
                  </section>
                </section>
              </section>
            </a>
            <!-- 加载动画 -->
            <loadmore v-show="loadingDom"></loadmore>
            <!-- 收益 -->
            <earningsPop ref="earnings"></earningsPop>
        </section>
      </section>
    </section>
  </div>
</template>
<script>
  import { InfiniteScroll, Indicator } from 'mint-ui'
  import goback from '../../components/goback'
  import loadmore from '../../components/loadmore'
  import { userInfoGet, WXShare } from '../../libs/publicMethod'  
  import { getGoodsList, product } from '../../libs/interface'
  import earningsPop from '../../components/earningsPop'
  export default {
    components:{ goback, loadmore, InfiniteScroll, userInfoGet, getGoodsList, product, earningsPop, WXShare, Indicator },
    data () {
      return {
        userInfo:userInfoGet(),// 用户类型
        goName: "分类", // 导航名称
        goType: '', // 导航返回页面，如返回上一级则为空
        goBtn: '', // 导航右边菜单，如没有则不填
        seachCnt: '', // 搜索框内容
        loading: false, // 下拉参数
        loadingDom: false,
        categoryList: sessionStorage.getItem('categoryList')?JSON.parse(sessionStorage.getItem('categoryList')):[], // 商品分类列表
        goodsList: [],//商品列表
        offset: sessionStorage.getItem('categoryScrollOffset') ? JSON.parse(sessionStorage.getItem('categoryScrollOffset')).offset || 0 : 0,
        sortField: sessionStorage.getItem('sortField')?sessionStorage.getItem('sortField'):'sell', //排序字段
        saleSort: sessionStorage.getItem('saleSort')?sessionStorage.getItem('saleSort'):'DESC', // 销量排序
        priceSort: sessionStorage.getItem('priceSort')?sessionStorage.getItem('priceSort'):'DESC', // 价钱排序，
        ifShowTwo: false,
        twoLevelMenu: ['全部', '手机', '电脑', '游戏', '床上用品'],
        firstId: '',
      }
    },
    mounted () {
      let vm = this
      if (!sessionStorage.getItem('categoryScrollOffset')) {
        !sessionStorage.getItem('categoryList') ? vm.getGoodsList() : vm.Initialize(0)
        let params = {
          parentId: 7
        }
        getGoodsList(params, (data) => {
          if (data.code === 1) {
            // sessionStorage.removeItem('categoryScrollOffset')
            vm.ifShowTwo = true
            vm.twoLevelMenu = data.payload
          } else {
            vm.$toast('暂未请求到数据,请稍后再试')
          }
        })
      } else {
        vm.ifShowTwo = false
        !sessionStorage.getItem('categoryList') ? vm.getGoodsList() : vm.Initialize(JSON.parse(sessionStorage.getItem('categoryScrollOffset')).oneLevelId)
        // params.parentId = JSON.parse(sessionStorage.getItem('categoryScrollOffset')).oneLevelId
        vm.turnTwoLevel(JSON.parse(sessionStorage.getItem('categoryScrollOffset')).twoLevelId)
        let categoryScrollOffset = JSON.parse(sessionStorage.getItem('categoryScrollOffset'))
        categoryScrollOffset.offset += 10
        let param = {
          productType: vm.$route.params.id,
          runType: -1,
          limit: 10,
          offset: 0,
          likeStr: vm.seachCnt,
          sidx: vm.sortField,
          sord: vm.saleSort ? vm.saleSort : vm.priceSort
        }
        param.limit = categoryScrollOffset.offset
        product(param, (data) => {
          if (data.code === 1 && data.payload.length > 0) {
            vm.goodsList = data.payload
            vm.$nextTick(() => {
              vm.$refs.goodsList.scrollTop = categoryScrollOffset.scroll
              setTimeout(() => {
                sessionStorage.removeItem('categoryScrollOffset')
              }, 0)
            })
          } else {
            vm.$toast('暂未请求到数据,请稍后再试')
          }
        })
        // product(param, (data) => {
        //   if (data.code === 1 && data.payload.length > 0) {
        //     vm.goodsList = data.payload
        //   } else {
        //     vm.$toast('暂未请求到数据,请稍后再试')
        //   }
        // });
      }
      WXShare.hideOptionMenu()
    },
    methods: {
      turnTwoLevel (id) {
        let vm = this
        // vm.offset = sessionStorage.getItem('categoryScrollOffset') ? JSON.parse(sessionStorage.getItem('categoryScrollOffset')).offset || 0 : 0
        let params = {
          productType: id,
          runType: -1,
          limit: 10,
          // offset: vm.offset,
          offset: 0,
          likeStr: vm.seachCnt,
          sidx: vm.sortField,
          sord: vm.saleSort ? vm.saleSort : vm.priceSort
        }
        product(params, (data) => {
          if (data.code === 1) {
            vm.$router.replace('/category/' + vm.$route.params.column + '/' + id)
            vm.goodsList = data.payload;
            vm.ifShowTwo = false
          }
        })
      },
      showTwoLevel (id) {
        let vm = this
        vm.$refs.goodsList.scrollTop = 0
        vm.loading = false
        vm.goodsList = []
        vm.seachCnt = ''
        Indicator.open({
          spinnerType: 'fading-circle'
        })
        let params = {
          parentId: id
        }
        getGoodsList(params, (data) => {
          if (data.code === 1) {
            vm.$router.replace('/category/' + id + '/0' )
            Indicator.close()
            if (data.payload.length === 0) {
              vm.$toast('该分类暂无商品')
            }
            vm.twoLevelMenu = data.payload
            vm.ifShowTwo = true
            // sessionStorage.setItem('categoryList', JSON.stringify(data.payload));
            // vm.Initialize(vm.$route.params.id)
          } else {
            vm.$toast('暂未请求到数据,请稍后再试')
          }
        })
      },
      // 初始化
      Initialize (val) {
        let vm = this
        // vm.seachFnc(vm.sortField);
        vm.$refs.goodsList_s.scrollTop = 0;
        vm.$refs.goods_category.childNodes.forEach(element => {
          element.style='rgba(246,246,246,1)'
          element.childNodes[0].style='color:rgba(132,132,132,1);'
          element.childNodes[1].style='display:none'
        });
        vm.$refs.goods_category.childNodes[val].childNodes[0].style='color:rgba(45,45,45,1);'
        vm.$refs.goods_category.childNodes[val].childNodes[1].style='display:block;'
        vm.$refs.goods_category.childNodes[val].style='background:rgba(255,255,255,1);'
      },
      // 搜索
      seach () {
        let vm = this
        // vm.$router.replace('/category/'+-1+'/'+0);
        let params = {
          productType: -1,
          runType: -1,
          limit: 10,
          offset: 0,
          likeStr: vm.seachCnt,
          sidx: vm.sortField,
          sord: vm.saleSort?vm.saleSort:vm.priceSort
        }
        product(params,(data)=>{
          if (data.code === 1) {
            vm.ifShowTwo = false
            vm.goodsList = data.payload
          }
        })
      },
      // 跳转详情页
      seeSec (val) {
        let vm = this
        // sessionStorage.setItem('coupon', JSON.stringify({ coupon: false, isFund: false }))
        sessionStorage.removeItem('coupon')
        vm.categoryList.forEach((e,i) => {
          if (e.id == vm.$route.params.column) {
            sessionStorage.setItem('categoryScrollOffset', JSON.stringify({ scroll: vm.$refs.goodsList.scrollTop, offset: vm.offset, oneLevelId: i, twoLevelId: vm.$route.params.id }))
          }
        })
        vm.$router.push('/goods/' + val)
      },
      // 查看收益
      lookEarnings (clearPrice, defaultPrice) {
        let vm = this
        vm.$refs.earnings.showbox(true);
        vm.$refs.earnings.computeEarnings(clearPrice, defaultPrice);
      },
      // 点击菜单加载--刷新页面后加载
      seachFnc (val) {
        let vm = this
        switch (val) {
          case 'sell':
            if (vm.saleSort == 'ASC') {
              vm.sortFncS('sell','ASC')
            } else {
              vm.sortFncS('sell','DESC')
            }
            break;
          case 'defaultPrice':
            if (vm.priceSort == 'ASC') {
              vm.sortFncS('defaultPrice','ASC')
            } else {
              vm.sortFncS('defaultPrice','DESC')
            }
            break;
        }
      },
      // 排序
      sortFnc (val) {
        let vm = this
        vm.loading = false
        vm.offset = 0
        vm.$refs.goodsList_s.scrollTop = 0
        sessionStorage.setItem('sortField', val)
        vm.sortField = val
        switch (val) {
          case 'sell':
            if (vm.saleSort == 'ASC') {
              vm.saleSort = 'DESC'
              vm.sortFncS('sell','DESC')
              sessionStorage.setItem('saleSort', 'DESC')
            } else {
              vm.saleSort = 'ASC'
              vm.sortFncS('sell','ASC')
              sessionStorage.setItem('saleSort', 'ASC')
            }
            break;
          case 'defaultPrice':
            if (vm.priceSort == 'ASC') {
              vm.priceSort = 'DESC'
              vm.sortFncS('defaultPrice','DESC')
              sessionStorage.setItem('priceSort', 'DESC')
            } else {
              vm.priceSort = 'ASC'
              vm.sortFncS('defaultPrice','ASC')
              sessionStorage.setItem('priceSort', 'ASC')
            }
            break;
        }
      },
      sortFncS (sidx,sord){
        let vm = this
        let params = {
          productType: vm.$route.params.id,
          runType: -1,
          limit: 10,
          offset: 0,
          likeStr: vm.seachCnt,
          sidx: sidx,
          sord: sord
        }
        if (sessionStorage.getItem('categoryScrollOffset')) {
          let categorySO = JSON.parse(sessionStorage.getItem('categoryScrollOffset'))
          categorySO.offset += 10
          params.limit = categorySO.offset
          product(params, (data) => {
            if (data.code === 1 && data.payload.length > 0) {
              vm.goodsList = data.payload
              vm.$nextTick(() => {
                vm.$refs.goodsList.scrollTop = categorySO.scroll
                setTimeout(() => {
                  sessionStorage.removeItem('categoryScrollOffset')
                }, 0)
              })
            } else {
              vm.goodsList = []
              if (data.code === 0) {
                vm.$toast('暂未请求到数据,请稍后再试')
              } else {
                // vm.$toast('该分类下暂无商品')
              }
            }
          })
        } else {
          product(params, (data) => {
            if (data.code === 1 && data.payload.length > 0) {
              vm.goodsList = data.payload
            } else {
              vm.goodsList = []
              if (data.code === 0) {
                vm.$toast('暂未请求到数据,请稍后再试')
              } else {
                // vm.$toast('该分类下暂无商品')
              }
            }
          })
        }
      },
      // 上拉加载更多
      loadMore() {
        let vm = this
        if (sessionStorage.getItem('categoryScrollOffset')) return null
        vm.loading = true
        vm.loadingDom = true
        vm.offset += 10
        let params = {
          productType: vm.$route.params.id,
          runType: -1,
          limit: 10,
          offset: vm.offset,
          likeStr: vm.seachCnt,
          sidx: vm.sortField,
          sord: vm.saleSort?vm.saleSort:vm.priceSort
        }
        product(params,(data)=>{          
          if (data.code === 1 && data.payload.length > 0) {
            vm.$nextTick(()=>{
              data.payload.forEach((item) => {              
                vm.goodsList.push(item)
              })
            })
            vm.loading = false
          } else {
            vm.loading = true
            vm.offset -= 10
            vm.$toast('暂未请求到数据,请稍后再试')
          }
          vm.loadingDom = false
        })
      },
      // 获取商品属性列表
      getGoodsList () {
        let vm = this
        let params = {
          parentId: 0
        }
        getGoodsList(params,(data) => {
          if (data.code === 1 && data.payload.length>0) {
            vm.categoryList = data.payload
            vm.firstId = vm.categoryList[0].id
            sessionStorage.setItem('categoryList',JSON.stringify(data.payload))
            vm.Initialize(0)
          } else {
            vm.Initialize(0)
            // vm.$toast('暂未请求到数据,请稍后再试')
          }
        })
      }
    },
    filters: {
      currency: function (value) {
        if (!value) return ''
        return '￥' + value
      }
    }
  }
</script>
<style scoped>
*{
  box-sizing: border-box;
}
a{
  text-decoration: none;
  outline: none;
  color: black;
  -webkit-tap-highlight-color:rgba(255,0,0,0)
}
.category{
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: white!important;
}
/* 搜索框 */
.seach{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  text-align: center;
  padding: .5rem 1rem;
  background-color: white;
}
.seach input{
  padding: .5rem;
  border-radius: 1rem;
  border: 1px solid #aaa;
  outline: none;
  width: 80%;
}
.seach section{
  width: 1.5rem;
}
.seach section img{
  width: 100%;
}
/* 商品区 */
.goods{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  width: 100%;
  height: 87%;
}
/* 左边菜单 */
.goods_category{  
  width: 30%;
  height: 100%;
  overflow: auto;
  background-color: rgba(246,246,246,1);
}
.goods_category>section{
  position: relative;
  color: rgba(132,132,132,1);
  background:rgba(246,246,246,1);
}
.goods_category>section a{
  display: inline-block;
  width: 100%;
  box-sizing: border-box;
  padding: 1.2rem 2%;
}
.redBox{
  position: absolute;
  height: 30%;
  width: .3rem;
  background-color: rgba(226,35,25,1);
  top: 35%;
  left: 0;
  display: none;
}
/* 商品详情 */
.goodsList{
  width:70%;
  background-color: rgba(255,255,255,1);
  padding: .5rem;
  overflow: auto;
  position: relative;
  margin-bottom: 1rem;
  padding-top: 0;
}
.goodsList .goodsList_s{
  margin-top: 2rem;
}
/* 排序 */
.seachTit{  
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  text-align: center;
  font-size: .8rem;
  padding-bottom: .3rem;
  position: fixed;
  width: 70%;
  z-index: 10;
  background: white;
  flex-wrap: wrap;
}
.seachTit span{
  white-space: nowrap;
}
.seachTit section{
  display: flex;
  flex-direction: row;
  align-items: center;
  text-align: center;
}
.seachTit img{
  height: 1.2rem;
  margin-left: .5rem;
}
/* 商品详情 */
.goodsList_sec{
  width: 100%;  
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  text-align: left;
  box-sizing: border-box;
  border-radius:1rem;
  box-shadow:1px 1px 8px rgba(185,182,168,0.5);
  margin-top: .5rem;
  overflow: hidden;
  position:relative;
}
._img{
  width: 55%;
  height: 6.75rem;
}
._img img{
  width: 100%;
  height: 100%;
}
._sec{
  height: 6.75rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: left;
  width: 45%;
  font-size: .75rem;
  padding: .6rem .3rem;
  box-sizing: border-box;
}
._sec ._sec_tit{
  display: block;
  width: 100%;
  overflow : hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  color:#333333;
}
._sec ._sec_price{
  font-size: .8rem;
  font-family:MicrosoftYaHei-Bold;
  color:rgba(242,48,48,1);
  text-align: left;
}

._sec ._sec_btn{ 
  width: 100%; 
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
._sec_btn .cateSec{
    border: 1px solid #999;
    padding: .2rem .3rem;
    border-radius: 1rem;
    font-size: .6rem;
}
._sec_btn .cateImg{
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    border: 1px solid rgba(231, 224, 255,.8);
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    text-align: center;
    padding: .3rem;
    -webkit-box-sizing: border-box;
    box-sizing: border-box
}
._sec_btn img{
  height: 100%;
}
.twoLevelMenu{
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #fff;
  left: -1px;
  z-index: 11;
}
.classfify{
  width: 77%;
  margin: 0 auto;
  display: flex;
  /* background-color: blue; */
  flex-wrap: wrap;
}
.twoLevelClass{
  margin-top: 5%;
  padding: 4%;
  height: 2rem;
  border-left: 2px solid #E0E0E0;
  color: #333;
  font-size: .8rem;
  cursor: pointer;
}

</style>
